<template>
    <div class="dept-management">
      <div class="header">
        <h2>部门管理</h2>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增部门
        </el-button>
      </div>
  
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :model="searchForm" inline>
          <el-form-item label="部门名称">
            <el-input
              v-model="searchForm.deptName"
              placeholder="请输入部门名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 200px"
            >
              <el-option label="启用" :value="1" />
              <el-option label="停用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
  
      <!-- 表格区域 -->
      <div class="table-container">
        <el-table
          :data="tableData"
          v-loading="loading"
          border
          stripe
          style="width: 100%"
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column prop="deptName" label="部门名称" min-width="200" />
          <el-table-column prop="parentName" label="上级部门" min-width="150" />
          <el-table-column prop="leader" label="负责人" width="120" />
          <el-table-column prop="phone" label="联系电话" width="130" />
          <el-table-column prop="email" label="邮箱" min-width="150" />
          <el-table-column prop="sort" label="排序" width="80" align="center" />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '启用' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="{ row }">
              <div class="action-grid">
                <!-- 第一行 -->
                <div class="action-row">
                  <el-button size="small" @click="handleAddChild(row)" class="action-btn">
                    新增子部门
                  </el-button>
                  <el-button size="small" @click="handleEdit(row)" class="action-btn">
                    编辑
                  </el-button>
                </div>
                <!-- 第二行 -->
                <div class="action-row">
                  <el-button 
                    size="small" 
                    :type="row.status === 1 ? 'warning' : 'success'"
                    @click="handleUpdateStatus(row)"
                    class="action-btn"
                  >
                    {{ row.status === 1 ? '停用' : '启用' }}
                  </el-button>
                  <el-button 
                    size="small" 
                    type="danger" 
                    @click="handleDelete(row)"
                    class="action-btn"
                    :loading="deleteLoading === row.id"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
  
      <!-- 新增/编辑对话框 -->
      <DeptFormDialog
        v-model="dialogVisible"
        :form-data="currentDept"
        :is-edit="isEdit"
        :parent-dept="parentDept"
        @success="handleDialogSuccess"
      />
  
      <!-- 状态变更对话框 -->
      <el-dialog
        v-model="statusDialogVisible"
        :title="`${currentStatusDept.status === 1 ? '停用' : '启用'}部门`"
        width="400px"
        :before-close="handleStatusDialogClose"
      >
        <div class="status-dialog-content">
          <p>确定要{{ currentStatusDept.status === 1 ? '停用' : '启用' }}部门 <strong>"{{ currentStatusDept.deptName }}"</strong> 吗？</p>
          <p v-if="currentStatusDept.status === 1" class="warning-text">
            ⚠️ 停用后，该部门及其子部门将不可用
          </p>
        </div>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleStatusDialogClose">取消</el-button>
            <el-button 
              :type="currentStatusDept.status === 1 ? 'warning' : 'success'"
              @click="handleStatusConfirm"
              :loading="statusLoading"
            >
              {{ statusLoading ? '提交中...' : '确定' }}
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Plus, Search, Refresh } from '@element-plus/icons-vue'
  import { deptApi } from '@/api/dept'
  import DeptFormDialog from './components/DeptFormDialog.vue'
  
  // 响应式数据
  const loading = ref(false)
  const deleteLoading = ref(null)
  const statusLoading = ref(null)
  const dialogVisible = ref(false)
  const statusDialogVisible = ref(false)
  const isEdit = ref(false)
  const currentDept = ref({})
  const parentDept = ref({})
  const currentStatusDept = ref({})
  
  // 搜索表单
  const searchForm = reactive({
    deptName: '',
    status: null
  })
  
  // 分页数据
  const pagination = reactive({
    page: 1,
    size: 10,
    total: 0
  })
  
  // 表格数据
  const tableData = ref([])
  
  // 生命周期
  onMounted(() => {
    loadDeptList()
  })
  
  // 加载部门列表
  const loadDeptList = async () => {
    try {
      loading.value = true
      const response = await deptApi.getDeptList()
      
      if (response && response.code === 1) {
        tableData.value = response.data || []
        // 构建树形结构
        buildDeptTree(tableData.value)
        pagination.total = tableData.value.length
      } else {
        ElMessage.error(response?.msg || '获取部门列表失败')
        tableData.value = []
        pagination.total = 0
      }
    } catch (error) {
      ElMessage.error('网络错误，请稍后重试')
      tableData.value = []
      pagination.total = 0
    } finally {
      loading.value = false
    }
  }
  
  // 构建部门树形结构
  const buildDeptTree = (depts) => {
    const deptMap = new Map()
    const rootDepts = []
    
    // 建立id到部门的映射
    depts.forEach(dept => {
      deptMap.set(dept.id, { ...dept, children: [] })
    })
    
    // 构建树形结构
    depts.forEach(dept => {
      const node = deptMap.get(dept.id)
      if (dept.parentId === 0 || !deptMap.has(dept.parentId)) {
        rootDepts.push(node)
      } else {
        const parent = deptMap.get(dept.parentId)
        if (parent) {
          parent.children.push(node)
        }
      }
    })
    
    tableData.value = rootDepts
  }
  
  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    loadDeptList()
  }
  
  // 重置
  const handleReset = () => {
    Object.assign(searchForm, {
      deptName: '',
      status: null
    })
    pagination.page = 1
    loadDeptList()
  }
  
  // 分页大小改变
  const handleSizeChange = (size) => {
    pagination.size = size
    pagination.page = 1
    loadDeptList()
  }
  
  // 当前页改变
  const handleCurrentChange = (page) => {
    pagination.page = page
    loadDeptList()
  }
  
  // 新增部门
  const handleAdd = () => {
    isEdit.value = false
    parentDept.value = {}
    currentDept.value = {
      parentId: 0,
      deptName: '',
      leader: '',
      phone: '',
      email: '',
      sort: 0,
      status: 1
    }
    dialogVisible.value = true
  }
  
  // 新增子部门
  const handleAddChild = (row) => {
    isEdit.value = false
    parentDept.value = row
    currentDept.value = {
      parentId: row.id,
      deptName: '',
      leader: '',
      phone: '',
      email: '',
      sort: 0,
      status: 1
    }
    dialogVisible.value = true
  }
  
  // 编辑部门
  const handleEdit = (row) => {
    isEdit.value = true
    parentDept.value = {}
    currentDept.value = { ...row }
    dialogVisible.value = true
  }
  
  // 更新部门状态
  const handleUpdateStatus = (row) => {
    currentStatusDept.value = { ...row }
    statusDialogVisible.value = true
  }
  
  // 状态变更确认
  const handleStatusConfirm = async () => {
    try {
      statusLoading.value = true
      const newStatus = currentStatusDept.value.status === 1 ? 0 : 1
      
      const response = await deptApi.updateDeptStatus(currentStatusDept.value.id, newStatus)
      
      if (response.code === 1) {
        ElMessage.success(`${currentStatusDept.value.status === 1 ? '停用' : '启用'}部门成功`)
        handleStatusDialogClose()
        loadDeptList()
      } else {
        ElMessage.error(response.msg || '操作失败')
      }
    } catch (error) {
      ElMessage.error('操作失败')
    } finally {
      statusLoading.value = false
    }
  }
  
  // 关闭状态变更对话框
  const handleStatusDialogClose = () => {
    statusDialogVisible.value = false
    setTimeout(() => {
      currentStatusDept.value = {}
    }, 300)
  }
  
  // 删除部门
  const handleDelete = async (row) => {
    try {
      await ElMessageBox.confirm(
        `确定要删除部门 "${row.deptName}" 吗？此操作不可恢复！`,
        '警告',
        {
          type: 'warning',
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          confirmButtonClass: 'el-button--danger'
        }
      )
      
      deleteLoading.value = row.id
      
      const response = await deptApi.deleteDept(row.id)
      
      if (response.code === 1) {
        ElMessage.success('删除部门成功')
        loadDeptList()
      } else {
        ElMessage.error(response.msg || '删除部门失败')
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    } finally {
      deleteLoading.value = null
    }
  }
  
  // 对话框操作成功
  const handleDialogSuccess = () => {
    dialogVisible.value = false
    loadDeptList()
  }
  
  // 格式化日期时间
  const formatDateTime = (dateString) => {
    if (!dateString) return ''
    try {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    } catch (e) {
      return dateString
    }
  }
  </script>
  
  <style scoped>
  .dept-management {
    padding: 20px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
  }
  
  .search-container {
    margin-bottom: 20px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 4px;
  }
  
  .table-container {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
  
  /* 操作栏网格布局 */
  .action-grid {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  
  .action-row {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 8px;
  }
  
  .action-btn {
    flex: 1;
    min-width: 70px;
    max-width: 80px;
    font-size: 12px;
    padding: 6px 8px;
  }
  
  /* 状态变更对话框样式 */
  .status-dialog-content {
    padding: 10px 0;
  }
  
  .warning-text {
    color: #e6a23c;
    font-size: 14px;
    margin-top: 10px;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 10px;
  }
  
  :deep(.el-form-item) {
    margin-bottom: 0;
    margin-right: 10px;
  }
  </style>